<script lang="ts" setup>
import moment from 'moment'
import { Tag } from 'vant'
import { JobRecordApi } from '~/api/JobRecordApi'
import LxNavigationMenu from '~/components/LxNavigationMenu.vue'
import LxEntry from '~/components/common/LxEntry.vue'
import { JobRecordModel } from '~/model/JobRecordModel'

const route = useRoute()
const router = useRouter()
const menuShown = ref(false)
const records = ref([] as JobRecordModel[])

onMounted(() => {
  console.log(route)
  console.log(router)

  JobRecordApi.getAll()
    .then((res) => {
      records.value = res
      records.value.sort((a, b) => b.id - a.id)
    })
})

function dateFormatter(r: JobRecordModel) {
  return moment(r.date).format('MM/DD')
}

function contentFormatter(r: JobRecordModel) {
  return `${r.worker!.name}${r.description()}`
}

interface Sorter {
  name: string
  sort: (a: JobRecordModel, b: JobRecordModel) => number
}
const sorters: Sorter[] = [
  {
    name: '时间顺序',
    sort: (a, b) => b.date.valueOf() - a.date.valueOf(),
  },
  {
    name: '创建顺序',
    sort: (a, b) => b.id - a.id,
  },
]
const sorterIndex = ref(0)
// const activeSorter = computed(() => sorters[sorterIndex.value])

watchEffect(() => {
  const sort = sorters[sorterIndex.value].sort
  records.value.sort(sort)
})

function goDetail(row: JobRecordModel) {
  router.push(`/jobs/events/detail?id=${row.id}`)
}

function backupAll() {
  router.push('/jobs/events/backup_all')
}
</script>

<template>
  <div p4>
    <div mb2 flex>
      <Tag
        v-for="(sorter, index) in sorters"
        :key="index"
        type="primary"
        size="large"
        mr
        :plain="sorterIndex !== index"
        @click="sorterIndex = index"
      >
        {{ sorter.name }}
      </Tag>
    </div>
    <div paper of-hidden p0>
      <table class="lx-table">
        <thead>
          <tr>
            <td>日期</td>
            <td>
              事务
            </td>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="(item, index) in records" :key="index"
            @click="goDetail(item)"
          >
            <td>
              {{ dateFormatter(item) }}
            </td>
            <td>
              {{ contentFormatter(item) }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <LxNavigationMenu v-model="menuShown">
      <LxEntry icon="downloads" title="备份" :action="backupAll" :grid="3" />
    </LxNavigationMenu>
  </div>
</template>

<style scoped>

</style>

<route lang="yaml">
meta:
  title: 全部事务
</route>
